package com.example.ble_demo.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ble_demo.bean.DeviceInfoBean
import com.example.ble_demo.databinding.ItemLayoutBinding

//生成一个RecyclerView的适配器 用于显示蓝牙设备列表
class BlueToothAdapter(diffCallback: ItemCallback<DeviceInfoBean>) :
    ListAdapter<DeviceInfoBean, BlueToothViewHolder>(diffCallback) {

    var onItemClickListener: ((DeviceInfoBean) -> Unit)? = null

    var onItemLongClickListener: ((DeviceInfoBean) -> Unit)? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlueToothViewHolder {
        val binding = ItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BlueToothViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BlueToothViewHolder, position: Int) {
        val device = getItem(position)
        holder.bind(device)
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(device)
        }
        holder.itemView.setOnLongClickListener {
            onItemLongClickListener?.invoke(device)
            true
        }
    }
}

//生成一个ViewHolder 用于显示蓝牙设备列表
class BlueToothViewHolder(private val binding: ItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
    fun bind(device: DeviceInfoBean) {
        binding.deviceNameTv.text = if (device.isBonded) device.name + "(已配对)" else device.name
    }

}

class DeviceInfoBeanDiff : ItemCallback<DeviceInfoBean>() {
    override fun areItemsTheSame(oldItem: DeviceInfoBean, newItem: DeviceInfoBean): Boolean {
        return oldItem.name == newItem.name && oldItem.mac == newItem.mac && oldItem.isBonded == newItem.isBonded && oldItem.isConnected == newItem.isConnected
    }


    override fun areContentsTheSame(oldItem: DeviceInfoBean, newItem: DeviceInfoBean): Boolean {
        return oldItem.name == newItem.name && oldItem.mac == newItem.mac && oldItem.isBonded == newItem.isBonded && oldItem.isConnected == newItem.isConnected
    }

}


